package com.bedpotato.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.bedpotato.po.ProxyPO;

public class BasicHttpMethod {
	HttpClient httpclient;
	HttpResponse response;

	public List<Cookie> getCookies() {
		return ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
	}

	public Map<String, String> getMapCookies() {
		Map<String, String> map = new HashMap<String, String>();
		List<Cookie> cookies = ((AbstractHttpClient) httpclient)
				.getCookieStore().getCookies();
		for (Cookie c : cookies) {
			map.put(c.getName(), c.getValue());
		}
		return map;
	}

	public String getCookie(String key) {
		for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore()
				.getCookies()) {
			if (c.getName().equals(key))
				return c.getValue();
		}
		return null;
	}

	public BasicHttpMethod() {
		httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.BROWSER_COMPATIBILITY);
		httpclient.getParams().setParameter(
				ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
		httpclient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				12000);
	}

	public String get(String url) throws Exception {
		HttpGet httpget = new HttpGet(url);
		httpget.setHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11");
		response = httpclient.execute(httpget);
		HttpEntity httpEntity = response.getEntity();
		String html = null;
		if (httpEntity != null) {

				StringBuilder stringBuilder = new StringBuilder();
				InputStream instream = httpEntity.getContent();
				BufferedReader in = new BufferedReader(new InputStreamReader(
						instream));
				String line;
				while ((line = in.readLine()) != null) {
					stringBuilder.append(line).append("\n");
				}
				html = stringBuilder.toString();
			
		}
		httpEntity.consumeContent();
		return html;
	}

	public String getByAnonymousProxy(String url, ProxyPO proxyPO)
			throws Exception {
		HttpGet httpget = new HttpGet(url);
		HttpHost proxy = new HttpHost(proxyPO.getIp(), Integer.valueOf(proxyPO
				.getPort()));
		// 对HttpClient对象设置代理
		httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
				proxy);
		response = httpclient.execute(httpget);
		HttpEntity httpEntity = response.getEntity();
		String html = null;
		if (httpEntity != null) {
			html = EntityUtils.toString(httpEntity);
			httpEntity.consumeContent();
		}
		// 取消代理
		httpclient.getParams()
				.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		return html;
	}

	public String post(String url, List<NameValuePair> nvps) throws Exception {
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		response = httpclient.execute(httppost);
		HttpEntity httpEntity = response.getEntity();
		String html = null;
		if (httpEntity != null) {
			html = EntityUtils.toString(httpEntity);
			httpEntity.consumeContent();
		}
		return html;
	}

	public String post(String url, Map<String, String> map) throws IOException {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) it.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			NameValuePair nvp = new BasicNameValuePair(key, value);
			nvps.add(nvp);
		}
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		response = httpclient.execute(httppost);
		HttpEntity httpEntity = response.getEntity();
		String html = null;
		if (httpEntity != null) {
			html = EntityUtils.toString(httpEntity);
			httpEntity.consumeContent();
		}
		return html;
	}

	public String post(String url, String str) throws Exception {
		httpclient.getConnectionManager().closeIdleConnections(30,
				TimeUnit.SECONDS);
		HttpPost httppost = new HttpPost(url);// "http://web-proxy.qq.com/conn_s"
		StringEntity reqEntity = new StringEntity(str);
		httppost.setEntity(reqEntity);
		response = httpclient.execute(httppost);
		HttpEntity httpEntity = response.getEntity();
		String html = null;
		if (httpEntity != null) {
			html = EntityUtils.toString(httpEntity);
			httpEntity.consumeContent();
		}
		return html;
	}

	public void getImg(String url, String path) throws IOException {
		HttpGet httpget = new HttpGet(url);
		response = httpclient.execute(httpget);
		HttpEntity httpEntity = response.getEntity();
		byte[] b = EntityUtils.toByteArray(httpEntity);
		File storeFile = new File(path);
		FileOutputStream output = new FileOutputStream(storeFile);
		output.write(b);
		output.close();
		if (httpEntity != null) {
			httpEntity.consumeContent();
		}
	}

	public void close() throws IOException {
		httpclient.getConnectionManager().shutdown();
	}

	public String getCharset(HttpEntity entity) {
		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) {
					charset = param.getValue();
				}
			}
		}
		return charset;
	}
}
